const User = require('../models/User');
const City = require('../models/City');
const axios = require('axios');
const UserCity = require('../models/UserCity');

// 添加城市
exports.addCity = async (req, res) => {
  const { cityName } = req.body;
  // req.user.id 现在是 user_id
  const userId = req.user.user_id;
  try {
    const response = await axios.get(
      `https://restapi.amap.com/v5/place/text?key=${process.env.AMAP_KEY}&keywords=${cityName}&types=090000&offset=1`
    );

    if (response.data.status !== '1' || !response.data.pois || response.data.pois.length === 0) {
      return res.status(404).json({ error: '未找到城市信息' });
    }

    const adcode = response.data.pois[0].adcode;
    const foundCity = await City.findOne({ where: { city_code: adcode } });

    let city;
    if (foundCity) {
      city = foundCity;
    } else {
      // 如果数据库中没有，则创建新城市
      city = await City.create({ city_name: cityName, city_code: adcode });
    }

    // 检查用户是否已收藏该城市
    const userCity = await UserCity.findOne({ where: { user_id: userId, city_id: city.city_id } });

    if (userCity) {
      return res.status(400).json({ error: '该城市已收藏' });
    }

    // 添加城市到用户的收藏，并设置为非默认
    await UserCity.create({ user_id: userId, city_id: city.city_id, is_default: false });
    res.status(200).json({ message: '城市添加成功', city });
  } catch (error) {
    console.error('添加城市失败:', error);
    res.status(500).json({ error: '城市添加失败', details: error.message });
  }
};

// 获取所有城市
exports.getAllCities = async (req, res) => {
  try {
    console.log('Attempting to fetch all cities...');
    const cities = await City.findAll();
    console.log('Successfully fetched cities. Count:', cities.length);
    console.log('Fetched cities data:', JSON.stringify(cities, null, 2));
    res.json(cities);
  } catch (error) {
    console.error('获取城市列表失败:', error);
    res.status(500).json({ 
      error: '获取城市列表失败',
      details: error.message
    });
  }
};

// 根据经纬度获取城市信息
exports.getCityByCoordinates = async (req, res) => {
  const { latitude, longitude } = req.query;
  console.log(`[getCityByCoordinates] 接收到经纬度: ${latitude}, ${longitude}`);

  if (!latitude || !longitude) {
    return res.status(400).json({ error: '缺少经纬度参数' });
  }

  try {
    // 调用高德地图逆地理编码 API
    const response = await axios.get(
      `https://restapi.amap.com/v3/geocode/regeo?key=${process.env.AMAP_KEY}&location=${longitude},${latitude}&output=json`
    );
    console.log(`[getCityByCoordinates] 逆地理编码API响应: ${JSON.stringify(response.data)}`);

    const regeocode = response.data.regeocode;
    if (!regeocode || !regeocode.addressComponent || !regeocode.addressComponent.city) {
      console.log('[getCityByCoordinates] 未能解析到城市信息，regeocode 或 city 为空。');
      return res.status(404).json({ error: '未能解析到城市信息' });
    }

    let cityName = regeocode.addressComponent.city;
    let cityCode = regeocode.addressComponent.adcode;

    // 如果城市为空数组（直辖市），则取 province
    if (Array.isArray(cityName) && cityName.length === 0) {
        cityName = regeocode.addressComponent.province;
        cityCode = regeocode.addressComponent.adcode;
    }
    console.log(`[getCityByCoordinates] 解析到的城市名称: ${cityName}, adcode: ${cityCode}`);
    
    // 查找数据库中是否存在该城市，优先使用 city_code 查找，然后是 name
    let city = await City.findOne({ where: { city_code: cityCode } });
    if (!city) {
        console.log(`[getCityByCoordinates] 数据库中未通过adcode找到城市，尝试通过名称查找: ${cityName}`);
        city = await City.findOne({ where: { name: cityName } }); // 假设 City 模型中的城市名称字段是 name
    }
    console.log(`[getCityByCoordinates] 数据库查找结果: ${JSON.stringify(city, null, 2)}`);

    if (city) {
      res.json(city);
    } else {
      console.log(`[getCityByCoordinates] 数据库中未找到匹配的城市: ${cityName}, adcode: ${cityCode}`);
      res.status(404).json({ error: '数据库中未找到匹配的城市', cityName: cityName, cityCode: cityCode });
    }
  } catch (error) {
    console.error('根据经纬度获取城市失败:', error);
    res.status(500).json({ 
      error: '根据经纬度获取城市失败',
      details: error.message
    });
  }
};

// 根据城市名称获取城市信息
exports.searchCityByName = async (req, res) => {
  try {
    const { cityName } = req.query;
    console.log(`Attempting to search for city by name: ${cityName}`);

    if (!cityName) {
      return res.status(400).json({ error: '请输入城市名称' });
    }

    const city = await City.findOne({
      where: { name: cityName } // Assuming 'name' is the field for city name in your City model
    });
    console.log('City.findOne result:', JSON.stringify(city, null, 2));

    if (city) {
      console.log(`Found city by name: ${city.name}`);
      res.status(200).json(city);
    } else {
      console.log(`City not found by name: ${cityName}`);
      res.status(404).json({ error: '未找到该城市', cityName: cityName });
    }
  } catch (error) {
    console.error('搜索城市失败:', error);
    res.status(500).json({
      error: '搜索城市失败',
      details: error.message
    });
  }
};